package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.util.RequiredPermission;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class Permissioninterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Employee employee = (Employee) request.getSession().getAttribute("USERSESSION");
        if (employee.isAdmin()){
            return true;
        }
        if( handler instanceof HandlerMethod){
            HandlerMethod method=(HandlerMethod) handler;
            RequiredPermission annotation = method.getMethodAnnotation(RequiredPermission.class);
            if(annotation==null){
                return true;
            }
            //拿到权限集合
            List<String> persessions = (List<String>) request.getSession().getAttribute("PERSESSION");
            //判断你自己的权限是否在权限集合中
            String expremission = annotation.expremission();
            if (!persessions.contains(expremission)) {
                response.sendRedirect("/nopermission");
                return false;
            }
        }
        //放行静态页面
        return true;
    }
}
